var contextMenus = {
    id:"addMount",
    title:"添加消费",
    contexts:["selection"]
}

chrome.contextMenus.create(contextMenus)

chrome.contextMenus.onClicked.addListener(function(data){
    if(data.menuItemId =="addMount"&&data.selectionText){
        var amount = parseFloat(data.selectionText);
    }

    chrome.storage.sync.get(["total","limit"],function({total,limit}){
        var lastTotal = 0;
        if(total){
            lastTotal = parseFloat(total);
        }
        var newTotal = lastTotal + amount;
        chrome.storage.sync.set({"total":newTotal},function(){
            if(newTotal > limit){
                var options = {
                    type:'basic',
                    iconUrl:'img/logo.png',
                    title:'金额超出限制',
                    message:'您的消费金额超出限制'
                }
                chrome.notifications.create(options)
            }
        })  
        // //更新UI
        // $("#total").text(newTotal);
        // $("#inp2").val('')
    })
})

chrome.storage.onChanged.addListener(function(changes,storageName){
    var newTotal = changes.total.newValue;
    chrome.browserAction.setBadgeText({"text":newTotal.toString()});
    chrome.storage.sync.get("limit",function({limit}){
        var limitVal=0;
        if(limit){
             limitVal = parseFloat(limit);
        }
        var color = "green"
        if(limitVal<newTotal){
            color='red'
        }
        chrome.browserAction.setBadgeBackgroundColor({"color":color})
    })
    
})